
import java.util.*;

/**
 * @Author 12629
 * @Description：
 */
public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //public TreeNode root;

    /**
     * 创建一棵二叉树 创建成功后 返回根节点
     * @return
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }

    // 前序遍历
    void preOrder(TreeNode root){
        if(root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    void preOrderNor(TreeNode root){
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    /*List<Integer> ret = new ArrayList<>();
    *//**
     * 把 前序遍历的结果 存储到List 当中
     * @param root
     * @return
     *//*
    public List<Integer> preorderTraversal(TreeNode root) {
        if(root == null) {
            return null;
        }
        ret.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return ret;
    }*/
    /*public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        list.add(root.val);
        List<Integer> leftTree = preorderTraversal(root.left);
        list.addAll(leftTree);
        List<Integer> rightTree = preorderTraversal(root.right);
        list.addAll(rightTree);
        return list;
    }*/
    // 中序遍历  -》 左根右
    void inOrder(TreeNode root){
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    void inOrderNor(TreeNode root){
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }


    // 后序遍历  -》 左右根
    void postOrder(TreeNode root){
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }


    void postOrderNor(TreeNode root){
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();

            if(top.right == null || top.right == prev) {
                System.out.print(top.val+" ");
                stack.pop();
                prev = top;
            }else {
                cur = top.right;
            }
        }
    }


    public int nodeSize;
    // 获取树中节点的个数
    int size(TreeNode root) {
        if(root == null) {
            return 0;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
        return nodeSize;
    }

    //子问题的思路解决
    int size2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return size2(root.left)+size2(root.right)+1;
    }

    public int leafSize;
    // 获取叶子节点的个数
    int getLeafNodeCount1(TreeNode root){
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
        return leafSize;
    }

    int getLeafNodeCount(TreeNode root){
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount(root.left)
                + getLeafNodeCount(root.right);

    }

    // 获取第K层节点的个数
    int getKLevelNodeCount(TreeNode root,int k) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1) +
                getKLevelNodeCount(root.right,k-1);
    }

    // 获取二叉树的高度 时间复杂度O(N)
    int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return leftHeight > rightHeight ? leftHeight+1:
                rightHeight+1;
    }

    int getHeight2(TreeNode root) {
        if(root == null) {
            return 0;
        }

        return getHeight2(root.left) > getHeight2(root.right)
                ? getHeight2(root.left)+1:
                getHeight2(root.right)+1;
    }


    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, char val) {
        if(root == null) {
            return null;
        }

        if(root.val == val) {
            return root;
        }
        TreeNode ret1 = find(root.left,val);
        if(ret1 != null) {
            return ret1;//不去右边了
        }

        TreeNode ret2 = find(root.right,val);
        if(ret2 != null) {
            return ret2;
        }

        return null;
    }


    /**
     * 时间复杂度：O min(m,n)
     * @param p  m
     * @param q  n
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if( (p == null && q != null) || (p != null && q == null)) {
            return false;
        }
        //上述代码走完之后 要么是两个都为空 要么是两个都不为空
        if(p == null && q == null) {
            return true;
        }
        //代码走到这里  两个都不为空
        if(p.val != q.val) {
            return false;
        }

        //p != null && q != null  && p.val == q.val
        return isSameTree(p.left,q.left)
                && isSameTree(p.right,q.right);

    }

    /**
     * O(M*N)
     *
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null || subRoot == null) {
            return false;
        }
        //1、是不是和根节点相同
        if(isSameTree(root,subRoot)) {
            return true;
        }
        //2、判断是不是root的左子树
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        //3、右子树
        if(isSubtree(root.right,subRoot)) {
            return true;
        }
        //4、返回
        return false;
    }


    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        if(root.left == null && root.right == null) {
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }
    //最坏情况下 每个节点 都要求高度
    //时间复杂度：O(N^2)
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int leftHeight =  maxDepth(root.left);
        int rightHeight =  maxDepth(root.right);

        return Math.abs(leftHeight - rightHeight) <= 1 &&
                isBalanced(root.left) && isBalanced(root.right);
    }

    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight =  maxDepth(root.left);
        int rightHeight =  maxDepth(root.right);
        return leftHeight > rightHeight
                ? leftHeight+1:
                rightHeight+1;
    }

    //O(n)的时间复杂度

    public boolean isBalanced2(TreeNode root) {
        if(root == null) {
            return true;
        }
        return maxDepth(root) >= 0;
    }

    public int maxDepth2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight =  maxDepth2(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        int rightHeight =  maxDepth2(root.right);
        if(leftHeight >= 0 && rightHeight >= 0
                && Math.abs(leftHeight-rightHeight) <= 1) {
            //在这种情况下 我才会返回 真实的高度
            return Math.max(leftHeight,rightHeight)+1;
        }else {
            return -1;
        }
    }


    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;

        return isSymmetricChild(root.left,root.right);
    }

    private boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if(leftTree != null && rightTree == null ||
                leftTree == null && rightTree != null) {
            return false;
        }
        if(leftTree == null &&rightTree == null) {
            return true;
        }
        if(leftTree.val != rightTree.val) {
            return false;
        }
        return isSymmetricChild(leftTree.left,rightTree.right) &&
                isSymmetricChild(leftTree.right,rightTree.left);
    }

    /*
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=60&&tqId=29483&rp=1&ru=/activity/oj&qru=/ta/tsing-kaoyan/question-ranking
    class TreeNode {

    public char val;

    public TreeNode left;
    public TreeNode right;

    public TreeNode(char val) {
        this.val = val;
    }
}


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static int i = 0;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();

            TreeNode root = createTree(str);

            inorder(root);
        }
    }

    public static TreeNode createTree(String str) {
        //1. 遍历字符串str
        // for(int i = 0;i < str.length();i++) {
        //     char ch = str.charAt(i);
        // }
        TreeNode root = null;
        if(str.charAt(i) != '#') {
            //2. 根据前序遍历创建二叉树
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        }else {
            i++;
        }
        //3.返回根节点
        return root;
    }

    public static void inorder(TreeNode root) {
        if(root == null) {
            return ;
        }
        inorder(root.left);

        System.out.print(root.val+" ");

        inorder(root.right);

    }

}
     */


    //层序遍历
    void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");

            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }


   /* public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);//A

        while (!queue.isEmpty()) {
            int size = queue.size();//1
            List<Integer> tmp = new ArrayList<>();
            while (size != 0) {
                TreeNode cur = queue.poll();
                //System.out.print(cur.val + " ");
                tmp.add(cur.val);
                size--;//0
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }*/
    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if(root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;//结束这个循环
            }
        }
        //需要判断队列当中 是否有非空的元素
        while (!queue.isEmpty()) {
            //一个元素 一个元素 出队来判断 是不是空
            TreeNode tmp = queue.peek();
            if(tmp == null) {
                queue.poll();
            }else {
                return false;
            }
        }
        return true;
    }


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        if(root == p || root == q) {
            return root;
        }
        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
        if(leftTree != null && rightTree != null) {
            return root;
        }else if(leftTree != null) {
            return leftTree;
        }else {
            return rightTree;
        }
    }


    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {

        if(root == null) return null;

        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();

        getPath(root,p,stackP);
        getPath(root,q,stackQ);

        int sizeP = stackP.size();
        int sizeQ = stackQ.size();

        if(sizeP > sizeQ) {
            int size = sizeP - sizeQ;
            while(size != 0) {
                stackP.pop();
                size--;
            }

        }else {
            int size = sizeQ - sizeP;
            while(size != 0) {
                stackQ.pop();
                size--;
            }
        }
        //两个栈当中的元素是一样多
        while(!stackP.isEmpty() && !stackQ.isEmpty()) {
            if(stackP.peek() == stackQ.peek()) {
                return stackP.peek();
            }else{
                stackP.pop();
                stackQ.pop();
            }
        }

        return null;
    }

    private boolean getPath(TreeNode root,TreeNode node,Stack<TreeNode> stack) {
        if(root == null || node == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flg = getPath(root.left,node,stack);
        if(flg) {
            return true;
        }
        boolean flg2 = getPath(root.right,node,stack);
        if(flg2) {
            return true;
        }

        stack.pop();

        return false;
    }

    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    private void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if(t == null) {
            return ;
        }
        stringBuilder.append(t.val);
        if(t.left != null) {
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(t.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }
        //判断右树
        if(t.right != null) {
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}




















